package main

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"time"

	"go.etcd.io/etcd/client/v3"
)

func main() {
	// 创建一个client
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatal(err)
	}

	defer cli.Close()

	// 创建一个watcher
	watcher := clientv3.NewWatcher(cli)
	defer watcher.Close()

	// 设置watch参数，这里设置为监视 以/class为前缀的所有key的变化
	watchStream := watcher.Watch(context.Background(), "/class", clientv3.WithPrefix())

	// 循环监视key的变化
	for resp := range watchStream {
		for _, ev := range resp.Events {
			fmt.Printf("%s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
			switch ev.Type {
			case clientv3.EventTypePut:
				fmt.Printf("Key %s created with value %s\n", ev.Kv.Key, ev.Kv.Value)
			case clientv3.EventTypeDelete:
				fmt.Printf("Key %s deleted\n", ev.Kv.Key)
				// Handle other event types if needed
			}

		}
	}
}
